import axios from 'axios'
import Vue from 'vue'

class AjaxWeb {
  constructor (dataHandle) {
    if (dataHandle) {
      this.dataHandle = dataHandle
    } else {
      this.dataHandle = function (data) {
        if (data.status === 200) {
          return data.result
        }
        return new Error(data.message)
      }
    }
  }
  ajax (config) {
    let { $loading: loading, $toast: toast } = Vue.prototype
    let { hasLoading = true } = config
    if (hasLoading) loading.show()
    if (process.env.NODE_ENV !== 'production') {
      config = {
        ...config,
        baseURL: require('@/dev.config.js').default.baseURL
      }
    }
    return axios(config).then(({ data }) => {
      const result = this.dataHandle(data)
      // 失败情况
      if (result instanceof Error) {
        return Promise.reject(result)
      }
      // 成功情况
      if (hasLoading) loading.hide()
      return result
    }).catch(e => {
      if (hasLoading) loading.hide()
      if (e.message) toast.error(e.message)
      return Promise.reject(e)
    })
  }
  get (url, config = {}) {
    return this.ajax(Object.assign({
      method: 'get',
      url
    }, config))
  }
  post (url, data, config = {}) {
    return this.ajax(Object.assign({
      method: 'post',
      url,
      data
    }, config))
  }
  // errorMsg (e) {
  //   let { message } = e
  //   if (!message) {
  //     if (e.__CANCEL__) {
  //       message = '用户取消'
  //     }
  //   }
  //   return message
  // }
}

// window.AjaxWeb = AjaxWeb

export default AjaxWeb
